#!/usr/bin/env python

import gtk
import logging

from gtkmvc.controller import Controller
from i18n.conf import _

log = logging.getLogger('controllers')

class ComplexToVector(object):
    def __init__(self, complex, scale=1.0):
        self.x = 0
        self.y = 0
        self.dx = float(complex.x) / scale
        self.dy = float(complex.y) / scale

class Vector(object):
    def __init__(self, vector_imp):
        self.vector_imp = vector_imp
    def draw(self, display, x=0, y=0):
        imp = self.vector_imp
        display.set_verts(imp.x + x, imp.y + y, imp.dx, imp.dy)

class MainController(Controller):
    def register_view(self, view):
        Controller.register_view(self, view) # Calls the overloaded method

        # Connects the exiting signal:
        view.get_top_widget().connect('destroy', self.quit)
        view.get_top_widget().show()
    def update(self):
        """Main function called periodic by gtk loop"""
        #log.debug(_('Updating...'))
        self.model.step()

        # Continue to call update forever
        return True
    # Signals
    def quit(self, *args):
        """Exit"""
        log.info(_('Quitting...'))
        return gtk.main_quit()
    def on_quit_button_clicked(self, button):
        self.quit()
    def on_vscale1_value_changed(self, vscale):
        """."""
        log.debug('vscale1 changed to %f', vscale.get_value())
        graph2 = self.view.graph2

        graph2.clear()
        graph2.arrow1.set_dx(vscale.get_value()/100)
        graph2.redraw()
    def on_vscale2_value_changed(self, vscale):
        """."""
        log.debug('vscale2 changed to %f', vscale.get_value())
        self.model.sistema.setPT(9550000 * vscale.get_value()/6.0)
    def on_button1_clicked(self, button):
        log.debug('button clicked')
    def property_sistema_after_change(self, model, sistema, name, res,
                                  args, kwargs):
        #log.debug('obj after change: %s %s %s %s %s', sistema, name, res, args, kwargs)
        phasor_diagram = self.view.phasor_diagram
        phasor_diagram.clear()
        #log.debug('sistema.v.x: %f, sistema.v.y: %f', sistema.v.x, sistema.v.y)
        sistema.report()
        v = Vector(ComplexToVector(sistema.v, scale=6000))
        vector_v_display = phasor_diagram.vector_v
        v.draw(vector_v_display, x=0.5, y=0.5)
        e = Vector(ComplexToVector(sistema.e, scale=6000))
        vector_e_display = phasor_diagram.vector_e
        e.draw(vector_e_display, x=0.5, y=0.5)

        phasor_diagram.redraw()


if __name__ == '__main__':
    #TODO: run tests
    pass

# vim:set shiftwidth=4 tabstop=4 expandtab ci textwidth=79:

